<template>
  <view class="container">
    <!-- 导航栏 -->
    <uni-nav-bar 
      dark 
      :fixed="true" 
      shadow 
      status-bar 
      left-icon="arrow-left" 
      title="走访看板" 
      @clickLeft="back" 
    />
    
    <!-- 日期范围选择栏 -->
    <view class="date-filter-bar">
      <text class="date-label">日期：</text>
      <uni-datetime-picker 
        v-model="dateRange" 
        type="daterange" 
        range-separator="~" 
		:clear-icon="false"
        start-placeholder="选择开始日期"
        end-placeholder="选择结束日期"
        @change="handleDateChange"
        class="date-picker"
      />
    </view>
    
    <!-- 主内容区 -->
    <view class="main-content">
      <view class="table-container">
        <!-- 滚动容器：仅纵向滚动 -->
        <view class="table-scroll-container" :style="{ height: scrollContainerHeight + 'px' }">
          <view class="data-table">
            <!-- 表头 -->
            <view class="table-header table-header-fixed">
              <view class="table-cell cell-rank" @click="handleSort('rank')">
                <view class="header-content">
                  <text>排名</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'rank' && sortConfig.type === 'asc' ? '#165DFF' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'rank' && sortConfig.type === 'desc' ? '#165DFF' : '#999'}">▼</text>
                  </view>
                </view>
              </view>
              <view class="table-cell cell-unitName" 
                    :class="isInitialState ? 'init-unitName' : ''"
                    @click="handleSort('unitName')">
                <view class="header-content header-center">
                  <text>单位名称</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'unitName' && sortConfig.type === 'asc' ? '#165DFF' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'unitName' && sortConfig.type === 'desc' ? '#165DFF' : '#999'}">▼</text>
                  </view>
                </view>
              </view>
              <view class="table-cell cell-visitCount" 
                    :class="isInitialState ? 'init-visitCount' : ''"
                    @click="handleSort('visitCount')">
                <view class="header-content header-center">
                  <text>走访数量</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" :style="{color: sortConfig.key === 'visitCount' && sortConfig.type === 'asc' ? '#165DFF' : '#999'}">▲</text>
                    <text class="sort-icon down-icon" :style="{color: sortConfig.key === 'visitCount' && sortConfig.type === 'desc' ? '#165DFF' : '#999'}">▼</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 表格内容 -->
            <view class="table-body">
              <view 
                class="table-row" 
                v-for="(item, index) in sortedTableData" 
                :key="'data-' + index"
                :class="index % 2 === 0 ? 'row-even' : 'row-odd'"
              >
                <view class="table-cell cell-rank">
                  <text class="rank-text">{{ item.rank }}</text>
                </view>
                <view class="table-cell cell-unitName" 
                      :class="isInitialState ? 'init-unitName' : ''">
                  <text 
                    :class="[
                      item.isInitData ? 'unit-name-has-underline' : 'unit-name-no-underline',
                      isInitialState ? 'text-center' : 'text-left'
                    ]"
                    @click="item.isInitData ? handleShowcode(item.code) : null"
                  >
                    {{ item.unitName }}
                  </text>
                </view>
                <view class="table-cell cell-visitCount" 
                      :class="isInitialState ? 'init-visitCount' : ''">
                  {{ item.visitCount }}
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 合计行：固定在底部 -->
        <view class="table-row total-tr table-row-fixed-bottom">
          <view class="table-cell cell-rank total-fixed-col">-</view>
          <view class="table-cell cell-unitName total-fixed-col"
                :class="isInitialState ? 'init-unitName' : ''">
            <text :class="isInitialState ? 'text-center' : 'text-left'">合计</text>
          </view>
          <view class="table-cell cell-visitCount"
                :class="isInitialState ? 'init-visitCount' : ''">
            {{ total.visitCount }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import store from '../../common/store.js'
import utils from '../../common/utils'

export default {
  data() {
    return {
      dateRange: this.getCurrentMonthRange(),
      tableData: [],
      total: { visitCount: 0 },
      sortConfig: { key: '', type: 'asc' },
      backBz: false,
      totalRowHeight: 55,
      scrollContainerHeight: 0,
      isInitialState: true
    };
  },
  computed: {
    sortedTableData() {
      const data = [...this.tableData];
      if (!this.sortConfig.key) return data;
      return data.sort((a, b) => {
        const valueA = a[this.sortConfig.key];
        const valueB = b[this.sortConfig.key];
        
        if (typeof valueA === 'number' && typeof valueB === 'number') {
          return this.sortConfig.type === 'asc' ? valueA - valueB : valueB - valueA;
        }
        
        if (typeof valueA === 'string' && typeof valueB === 'string') {
          return this.sortConfig.type === 'asc' 
            ? valueA.localeCompare(valueB, 'zh-CN') 
            : -valueA.localeCompare(valueB, 'zh-CN');
        }
        
        return 0;
      });
    },
    startDate() { return this.dateRange[0]; },
    endDate() { return this.dateRange[1]; }
  },
  onLoad() {
    this.$nextTick(() => {
      this.calculateScrollHeight();
      uni.onWindowResize(() => {
        this.$nextTick(() => this.calculateScrollHeight());
      });
    });
  },
  onUnload() {
    uni.offWindowResize();
  },
  onShow() {
    this.initPage().then(() => {
      this.$nextTick(() => this.calculateScrollHeight());
    });
  },
  methods: {
    getCurrentMonthRange() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      
      const format = (num) => num.toString().padStart(2, '0');
      
      const startDate = `${year}-${format(month + 1)}-${format(firstDay.getDate())}`;
      const endDate = `${year}-${format(month + 1)}-${format(lastDay.getDate())}`;
      
      return [startDate, endDate];
    },
    calculateScrollHeight() {
      const systemInfo = uni.getSystemInfoSync();
      const { windowHeight, safeArea } = systemInfo;
      const safeAreaBottom = safeArea?.bottom ? (windowHeight - safeArea.bottom) : 0;
      const navHeight = 44;
      const dateBarHeight = 50;
      const totalBarHeight = this.totalRowHeight + safeAreaBottom;

      this.scrollContainerHeight = windowHeight 
        - navHeight 
        - dateBarHeight 
        - totalBarHeight;

      if (this.scrollContainerHeight < 300) {
        this.scrollContainerHeight = 300;
      }
    },
    back() {
      if (this.backBz) {
        this.initPage().then(() => {
          this.isInitialState = true;
          this.$nextTick(() => this.calculateScrollHeight());
        });
      } else {
        uni.switchTab({
          url: '/pages/index/index',
          fail: (err) => {
            uni.redirectTo({
              url: '/pages/index/index',
              fail: (err2) => {
                console.error('跳转失败：', err2);
                uni.navigateBack();
              }
            });
          }
        });
      }
    },
    handleDateChange(newRange) {
      this.dateRange = newRange;
      this.initPage().then(() => {
        this.$nextTick(() => this.calculateScrollHeight());
      });
    },
    handleSort(key) {
      if (this.sortConfig.key === key) {
        this.sortConfig.type = this.sortConfig.type === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortConfig.key = key;
        this.sortConfig.type = 'asc';
      }
    },
    handleShowcode: async function(code) {
      this.backBz = true;
      this.isInitialState = false;
      this.$utils.showLoading("数据加载中...");
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        const enData = this.$utils.encrypt(
          JSON.stringify({ timestamp, ksrq: this.startDate, jsrq: this.endDate, jb: 3, jg_code: code }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        const res = await this.$myRequest.post_token(
          getApp().globalData.khzf + "/zfkb",
          { data: enData + "" }
        );
        this.$utils.hideLoading();
        if (res.code === 200) {
          const a = JSON.parse(utils.decrypt(res.data, userInfo.aesKey, userInfo.aesIv));
          const orgList = a.orgCountDTOList || [];
          
          const sortedOrgList = orgList.sort((x, y) => {
            if (y.totalCount !== x.totalCount) {
              return y.totalCount - x.totalCount;
            }
            return x.name.localeCompare(y.name, 'zh-CN');
          });
          
          this.tableData = sortedOrgList.map((orgItem, index) => ({
            rank: index + 1,
            unitName: this.formatUnitName(orgItem.name),
            visitCount: orgItem.totalCount,
            code: orgItem.code,
            isInitData: false
          }));
          
          this.total.visitCount = this.tableData.reduce((sum, item) => sum + item.visitCount, 0);
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
        }
      } catch (e) {
        this.$utils.hideLoading();
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);
      }
    },
    formatUnitName(name) {
      if (!name) return '';
      
      const prefixes = [
        "中国邮政集团有限公司武汉市",
        "中国邮政集团有限公司武汉",
		"中国邮政集团有限公司湖北",
        "中国邮政集团",
        "武汉市"
      ];
      
      let processedName = name;
      let hasChanged;
      
      do {
        hasChanged = false;
        for (const prefix of prefixes) {
          if (processedName.startsWith(prefix)) {
            processedName = processedName.replace(prefix, "").trim();
            hasChanged = true;
            break;
          }
        }
      } while (hasChanged);
      
      return processedName;
    },
    initPage: async function() {
      this.backBz = false;
      this.isInitialState = true;
      this.$utils.showLoading("数据加载中...");
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        const enData = this.$utils.encrypt(
          JSON.stringify({ timestamp, ksrq: this.startDate, jsrq: this.endDate, jb: 2 }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        const res = await this.$myRequest.post_token(
          getApp().globalData.khzf + "/zfkb",
          { data: enData + "" }
        );
        this.$utils.hideLoading();
        if (res.code === 200) {
          const a = JSON.parse(utils.decrypt(res.data, userInfo.aesKey, userInfo.aesIv));
          const orgList = a.orgCountDTOList || [];
          
          const sortedOrgList = orgList.sort((x, y) => {
            if (y.totalCount !== x.totalCount) {
              return y.totalCount - x.totalCount;
            }
            return x.name.localeCompare(y.name, 'zh-CN');
          });
          
          this.tableData = sortedOrgList.map((item, index) => ({
            rank: index + 1,
            unitName: this.formatUnitName(item.name),
            visitCount: item.totalCount,
            code: item.code,
            isInitData: true
          }));
          
          this.total.visitCount = this.tableData.reduce((sum, item) => sum + item.visitCount, 0);
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
        }
      } catch (e) {
        this.$utils.hideLoading();
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);
      }
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.date-filter-bar {
  background-color: #ffffff;
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
}
.date-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}
.date-picker {
  flex: 1;
}

.unit-name-has-underline {
  color: #333 !important;
  text-decoration: underline !important;
  text-underline-color: #333 !important;
  text-underline-offset: 2px;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: inline-block;
}

.unit-name-no-underline {
  color: #333 !important;
  cursor: default;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: inline-block;
}

.text-center {
  text-align: center !important;
  padding: 0 8px;
}
.text-left {
  text-align: left !important;
  padding-left: 10px;
}

/* 核心：初始状态列宽分配（排名列固定 + 后两列等宽） */
.cell-rank {
  width: 16% !important; /* 排名列占16% */
  min-width: 60px !important;
  max-width: 80px !important;
  flex: none !important;
  position: sticky;
  left: 0;
  z-index: 10;
  background-color: #f8f8f8;
}

/* 非初始状态默认宽度（可根据需求调整） */
.cell-unitName {
  width: 50% !important; 
  flex: none !important;
  position: sticky;
  left: 16%; /* 紧跟排名列右侧 */
  z-index: 9;
  background-color: #f8f8f8;
}
.cell-visitCount {
  width: 34% !important; 
  flex: none !important;
}

/* 初始状态：单位名称和走访数量列宽完全一致 */
.init-unitName, .init-visitCount {
  width: 42% !important; /* （100% - 16%）/ 2 = 42% */
  min-width: 120px !important; /* 确保两列不窄于120px */
  flex: none !important;
}

.header-center {
  justify-content: center !important;
  padding: 0 8px;
}

.row-even .cell-rank,
.row-even .cell-unitName {
  background-color: #ffffff;
}
.row-odd .cell-rank,
.row-odd .cell-unitName {
  background-color: #fef5f6;
}

.sort-icon-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1px;
  margin-left: 6px;
}
.sort-icon {
  font-size: 11px;
  line-height: 1;
  transition: color 0.2s ease;
}
.header-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.container {
  width: 100%;
  height: 100vh;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #ffffff;
}

.main-content {
  flex: 1;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
}

.table-container {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 禁止横向滚动，确保表格在屏幕内完整显示 */
.table-scroll-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  background-color: #ffffff;
}

.data-table {
  width: 100%;
  box-sizing: border-box;
}

.table-header {
  display: flex;
  background-color: #f8f8f8;
  color: #333;
  font-weight: 500;
  height: 48px;
  border-bottom: 1px solid #eee;
}
.table-header-fixed {
  position: sticky;
  top: 0;
  z-index: 20;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.table-body {
  display: flex;
  flex-direction: column;
}

.table-row {
  display: flex;
  width: 100%;
  height: 42px;
  border-bottom: 1px solid #eee;
}
.row-even {
  background-color: #ffffff;
}
.row-odd {
  background-color: #fef5f6;
}

.table-cell {
  padding: 0 8px;
  text-align: center;
  font-size: 14px;
  border-right: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  word-break: keep-all;
}
.table-header .table-cell:active {
  background-color: #eaeaea;
}
.table-cell:last-child {
  border-right: none;
}

.table-row-fixed-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 30;
  box-shadow: 0 -2px 4px rgba(0, 51, 153, 0.1);
  background-color: #165DFF !important;
}
.total-tr {
  color: #fff !important;
  font-weight: bold;
  height: 55px;
  border-bottom: none !important;
}
.total-tr .table-cell {
  color: #fff !important;
  border-right: 1px solid rgba(255, 255, 255, 0.3);
  border-bottom: none !important;
  font-size: 14px;
  align-items: center !important;
}
.total-fixed-col {
  background-color: #165DFF !important;
  z-index: 31;
}

@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
  .table-row-fixed-bottom {
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
  }
}

.rank-text {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.table-scroll-container::-webkit-scrollbar {
  width: 6px;
}
.table-scroll-container::-webkit-scrollbar-thumb {
  background-color: #165DFF;
  border-radius: 3px;
}
.table-scroll-container::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}
</style>